<template>
  <div class="s-canvas">
    <canvas
      id="s-canvas"
      :width="contentWidth"
      :height="contentHeight"
      @click="refreshCode">
    </canvas>
  </div>
</template>

<script>
export default {
  props: {
    identifyCode: { type: String, default: '1234' },
    fontSizeMin: { type: Number, default: 25 },
    fontSizeMax: { type: Number, default: 35 },
    contentWidth: { type: Number, default: 112 },
    contentHeight: { type: Number, default: 38 }
  },
  methods: {
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
      this.$emit('update:identifyCode', this.generateCode())
      this.drawPic()
    },
    drawPic() {
      const ctx = document.getElementById('s-canvas').getContext('2d')
      ctx.clearRect(0, 0, this.contentWidth, this.contentHeight)

      // 绘制干扰线（5条）
      for(let i = 0; i < 5; i++) {
        ctx.strokeStyle = this.randomColor(100, 200)
        ctx.beginPath()
        ctx.moveTo(
          this.randomNum(0, this.contentWidth),
          this.randomNum(0, this.contentHeight)
        )
        ctx.lineTo(
          this.randomNum(0, this.contentWidth),
          this.randomNum(0, this.contentHeight)
        )
        ctx.stroke()
      }

      // 绘制验证码文本
      for(let i = 0; i < this.identifyCode.length; i++) {
        ctx.font = `${this.randomNum(this.fontSizeMin, this.fontSizeMax)}px Arial`
        ctx.fillStyle = this.randomColor(50, 150)
        ctx.fillText(
          this.identifyCode[i],
          this.randomNum(5, 15) + i*(this.contentWidth/this.identifyCode.length),
          this.randomNum(this.fontSizeMax, this.contentHeight-5)
        )
      }
    }
  }
}
</script>
